package com.shxc.smarttrade.tigerwit.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.old.activity.BindBankActivity;
import com.shxc.smarttrade.old.activity.WithdrawResultActivity;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.tigerwit.model.CardListModel;
import com.shxc.smarttrade.tigerwit.model.WithdrawInfoModel;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 老虎 - 出金
 */
@ContentView(R.layout.activity_tigerwit_withdraw)
public class TigerWitWithdrawActivity extends BaseActivity {

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.rmb_textview)
    TextView rmb_textview;//约合人民币
    @ViewInject(R.id.rate_textview)
    TextView rate_textview;//当前汇率
    @ViewInject(R.id.edittext)
    EditText edittext;//输入框

    @ViewInject(R.id.waring_textview)
    TextView waring_textview;//提示信息
    @ViewInject(R.id.amount_textview)
    TextView amount_textview;//可提现金额
    @ViewInject(R.id.bank_name_textview)
    TextView bank_name_textview;//银行名称
    @ViewInject(R.id.card_info_textview)
    TextView card_info_textview;//银行卡信息


    private double rate = 0.0;
    private double money = 0.0;
    private double amount = 0.0;
    private boolean haveBankcard = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        title_textview.setText("出金");
        left_imageview.setVisibility(View.VISIBLE);
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        rate();
        cardList();
    }

    @Event({R.id.left_imageview, R.id.jump_textview})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                finish();
                break;
            case R.id.jump_textview:
                //前往出金

                //先请求服务器，获取流水号和计算后的金额
//                money = Double.parseDouble(edittext.getText().toString());

                Loger.e(money + "", amount + "");

                if (money < 20 || money > amount) {
                    ToastUtils.showToast("请按要求输入金额");
                } else {
                    if (haveBankcard) {
                        confirmwithdraw();
                    } else {
                        JumpTo(BindBankActivity.class);
                    }
                }
                break;
        }
    }

    /**
     * 初始化文本框监听器
     */
    private void initListener() {
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = edittext.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    money = 0;
                    rmb_textview.setText("约合人民币：¥ 0.00");
                    return;
                }

                try {
                    money = Double.parseDouble(text);
                    if (money < 20) {
                        rmb_textview.setText("约合人民币：¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                        money = 0;
                    } else {
                        rmb_textview.setText("约合人民币：¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                    }
                } catch (Exception e) {
                    ToastUtils.showToast("请输入正确金额");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //出金信息查询
    private void rate() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.DEPOSIT_TOWITHDRAW, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, WithdrawInfoModel.class);

                    if (jam.isSuccess()) {
                        WithdrawInfoModel model = (WithdrawInfoModel) jam.getData();
                        rate = model.getData().getRate();
                        rate_textview.setText("(当前汇率：1美元≈" + rate + "人民币)");
                        amount = model.getData().getAmount();
                        amount_textview.setText("可提现金额：$" + amount);
                        waring_textview.setVisibility(View.GONE);
                    } else {
                        try {
                            JSONObject resultJson = new JSONObject(response);
                            String resultCode = resultJson.getString("err_code");
                            if (resultCode.equals("-5")) {
                                waring_textview.setVisibility(View.VISIBLE);
                                waring_textview.setText(jam.getMsg());
                            } else {
                                ToastUtils.showToast(jam.getMsg());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //查询银行卡信息
    private void cardList() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.CARD_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CardListModel.class);
                    if (jam.isSuccess()) {
                        CardListModel model = (CardListModel) jam.getData();
                        if (model.getData().getCardInfo().size() > 0) {
                            bank_name_textview.setText(model.getData().getCardInfo().get(0).getBankName());
                            String num = model.getData().getCardInfo().get(0).getCardNo();
                            String newNum = "";
                            for (int i = 0; i < num.length(); i++) {
                                if (i < 4 || i > num.length() - 5) {
                                    newNum = newNum + num.substring(i, i + 1);
                                } else {
                                    newNum = newNum + "*";
                                }
                            }
                            card_info_textview.setText(newNum);
                            haveBankcard = true;
                        } else {
                            bank_name_textview.setText("暂无开卡信息");
                            card_info_textview.setText("暂无开卡信息");
                            haveBankcard = false;
                        }
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //提现
    private void confirmwithdraw() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        map.put("amount", money);
        MyOkHttpUtils.getServiceDatas(map, Contents.DEPOSIT_CONFIRMWITHDRAW, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        Intent intent = new Intent(TigerWitWithdrawActivity.this, WithdrawResultActivity.class);
                        intent.putExtra("rmbAmount", Arith.round4(Arith.mul(money, rate), 2));
                        intent.putExtra("dollar", money);
                        intent.putExtra("rate", rate);
                        intent.putExtra("status", 0);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }
}
